package com.example.port.Controller;

import com.example.port.dto.ApiResponse;
import com.example.port.entity.Cargo;
import com.example.port.service.CargoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.text.ParseException;
import java.text.SimpleDateFormat;

@RestController
@RequestMapping("/cargos")
public class CargoController {
    
    private final CargoService cargoService;
    
    @Autowired
    public CargoController(CargoService cargoService) {
        this.cargoService = cargoService;
    }
    
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public ApiResponse<Integer> createCargo(@RequestBody Cargo cargo) {
        int result = cargoService.insertCargo(cargo);
        if (result > 0) {
            return ApiResponse.success(result);
        }
        return ApiResponse.error(500, "创建货物信息失败");
    }
    
    @GetMapping
    public ApiResponse<List<Cargo>> getAllCargos() {
        List<Cargo> cargos = cargoService.getAllCargos();
        return ApiResponse.success(cargos);
    }
    
    @GetMapping("/{cargoId}")
    public ApiResponse<Cargo> getCargoById(@PathVariable Integer cargoId) {
        Cargo cargo = cargoService.getCargoById(cargoId);
        if (cargo != null) {
            return ApiResponse.success(cargo);
        }
        return ApiResponse.error(404, "未找到指定货物");
    }
    
    @GetMapping("/owner/{ownerId}")
    public ApiResponse<List<Cargo>> getCargosByOwnerId(@PathVariable Integer ownerId) {
        List<Cargo> cargos = cargoService.getCargosByOwnerId(ownerId);
        return ApiResponse.success(cargos);
    }
    
    @PutMapping("/{cargoId}")
    public ApiResponse<Integer> updateCargo(@PathVariable Integer cargoId, @RequestBody Cargo cargo) {
        cargo.setCargoId(cargoId);
        int result = cargoService.updateCargo(cargo);
        if (result > 0) {
            return ApiResponse.success(result);
        }
        return ApiResponse.error(500, "更新货物信息失败");
    }
    
    @DeleteMapping("/{cargoId}")
    public ApiResponse<Integer> deleteCargo(@PathVariable Integer cargoId) {
        int result = cargoService.deleteCargo(cargoId);
        if (result > 0) {
            return ApiResponse.success(result);
        }
        return ApiResponse.error(500, "删除货物信息失败");
    }
    
    /**
     * 货物出库接口
     * @param cargoId 货物ID
     * @param exitInfo 出库信息（actualExitTime, operatorName, exitNotes）
     * @return 处理结果
     */
    @PutMapping("/{cargoId}/exit")
    public ApiResponse<Integer> exitCargo(
            @PathVariable Integer cargoId,
            @RequestBody Map<String, Object> exitInfo) {
        
        try {
            // 从请求体中提取出库信息
            String actualExitTimeStr = (String) exitInfo.get("actualExitTime");
            String operatorName = (String) exitInfo.get("operatorName");
            String exitNotes = (String) exitInfo.get("exitNotes");
            
            // 将时间字符串转换为Date对象
            Date actualExitTime = null;
            if (actualExitTimeStr != null && !actualExitTimeStr.isEmpty()) {
                try {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    actualExitTime = format.parse(actualExitTimeStr);
                } catch (ParseException e) {
                    return ApiResponse.error(400, "出库时间格式错误");
                }
            } else {
                // 如果未提供出库时间，则使用当前时间
                actualExitTime = new Date();
            }
            
            // 调用服务层处理出库逻辑
            int result = cargoService.exitCargo(cargoId, actualExitTime, operatorName, exitNotes);
            
            if (result > 0) {
                return ApiResponse.success(result);
            } else {
                return ApiResponse.error(500, "货物出库失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.error(500, "处理货物出库时发生错误: " + e.getMessage());
        }
    }
} 
